package events

import (
	"github.com/boticord/backend/notifications/app"
	"github.com/boticord/backend/notifications/services"
	"github.com/boticord/backend/notifications/types"
	"github.com/gorilla/websocket"
	"go.uber.org/fx"
)

type AuthEventPayload struct {
	Token string `json:"token"`
}

func newAuthEvent() fx.Option {
	return fx.Module("AuthEvent", fx.Invoke(func(tok *services.AuthService, em *app.Emitter) {
		app.OnEvent[AuthEventPayload](em, "auth", func(c *websocket.Conn, id string, mt int, data app.Event[AuthEventPayload]) {
			info, err := tok.GetTokenInfo(data.Data.Token)
			if err != nil {
				app.Emit(c, "error", types.Error{
					Code:    types.ErrorCodeUnauthorized,
					Message: "Invalid token",
				})
				return
			}

			tok.SetSession(id, data.Data.Token, info)

			app.Emit(c, "hello", struct {
				ID string `json:"id"`
			}{
				ID: id,
			})
		})
	}))
}
